import path from 'path';
import ts from 'rollup-plugin-typescript2';
import json from 'rollup-plugin-json';
import resolvePlugin from 'rollup-plugin-node-resolve';
// 获得packages目录
const packagesDir = path.resolve(__dirname, 'packages');
// 获取打包的目录
const packageDir = path.resolve(packagesDir, process.env.TARGET);
// 获取打包目录的名字

// 解析路径
const resolve = (p) => path.resolve(packageDir, p);
const name = path.basename(packageDir);

// 获取打包目录下面的package.json中的自定义配置
const pkg = require(resolve('package.json'));
const pkgOptions = pkg.buildOptions;
const outputOptions = {
    'esm-builder': {
        file: resolve(`dist/${name}.esm-builder.js`),
        format: 'es'
    },
    'esm-browser': {
        file: resolve(`dist/${name}.esm-browser.js`),
        format: 'es'
    },
    'cjs': {
        file: resolve(`dist/${name}.cjs.js`),
        format: 'cjs'
    },
    'global': {
        file: resolve(`dist/${name}.global.js`),
        format: 'iife'
    }
}

function createOptions(format, output) {
    const entryFile = 'src/index.ts';
    const extensions = ['ts', 'js'];
    if (output.file.includes('global')) {
        output.name = pkgOptions.name;
    }
    const plugins = [
        ts({extensions}), // ts
        resolvePlugin(extensions), // 按node模块方式解析路径
        json() // 使用json文件

    ]
    return {
        input: resolve(entryFile), // 入口文件
        output, // 出口配置
        plugins // 插件
    }
}

const inlineFormat = process.env.FORMAT && process.env.FORMAT.split(',');
// 命令行传递的format参数大于pkgOptions中的format
const pkgFormat = inlineFormat || pkgOptions.format;

// 循环打包的format, 获取打包的最终配置

const buildOptions = pkgFormat.map(item => createOptions(item, outputOptions[item]))



export default buildOptions;